<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="utf-8">
	<meta http-equiv="x-ua-compatible" content="ie=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
	<title>裁剪</title>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.4.3/cropper.min.css">
	<style>
		.label {
			cursor: pointer;
		}

		.progress {
			display: none;
			margin-bottom: 1rem;
		}

		.alert {
			display: none;
		}

		.img-container {
			/* height: 500px; */
			height: 430px;
			/* height: 400px; */
			width: 300px;
			margin: 0 auto;
		}

		.img-container img {
			max-width: 100%;
		}
	</style>
</head>

<body>
	<div class="container">
		<h1>上传文章feature image并裁剪生成缩略图</h1>
		<label class="label" data-toggle="tooltip" title="生成缩略图">
			<img class="rounded" id="avatar" src="http://qiniu.xingtan.xyz/download%20%282%29.png" alt="avatar">
			<input type="file" class="sr-only" id="input" name="image" accept="image/*">
		</label>
		<div class="progress">
			<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="0"
				aria-valuemin="0" aria-valuemax="100">0%</div>
		</div>
		<div class="alert" role="alert"></div>
		<div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
			<div class="modal-dialog" role="document">
				<div class="modal-content">
					<div class="modal-header">
						<h5 class="modal-title" id="modalLabel">400x300 / 2 => 200x150</h5>
						<button type="button" class="close" data-dismiss="modal" aria-label="Close">
							<span aria-hidden="true">&times;</span>
						</button>
					</div>
					<div class="modal-body">
						<div class="img-container">
							<img id="image" src="http://qiniu.xingtan.xyz/2019_01_19_450278628_thumb.png">
						</div>
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
						<button type="button" class="btn btn-primary" id="crop">裁剪</button>
					</div>
				</div>
			</div>
		</div>

	</div>
	<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.bundle.min.js"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.4.3/cropper.min.js"></script>

	<script>
		window.addEventListener('DOMContentLoaded', function () {
			var avatar = document.getElementById('avatar');
			var image = document.getElementById('image');
			var input = document.getElementById('input');
			var $progress = $('.progress');
			var $progressBar = $('.progress-bar');
			var $alert = $('.alert');
			var $modal = $('#modal');
			var cropper;

			$('[data-toggle="tooltip"]').tooltip();

			input.addEventListener('change', function (e) {
				var files = e.target.files;
				var done = function (url) {
					input.value = '';
					image.src = url;
					$alert.hide();
					$modal.modal('show');
				};
				var reader;
				var file;
				var url;

				if (files && files.length > 0) {
					file = files[0];

					if (URL) {
						done(URL.createObjectURL(file));
					} else if (FileReader) {
						reader = new FileReader();
						reader.onload = function (e) {
							done(reader.result);
						};
						reader.readAsDataURL(file);
					}
				}
			});

			$modal.on('shown.bs.modal', function () {
				cropper = new Cropper(image, {
					aspectRatio: 150 / 200,
					viewMode: 1,
					dragMode: 'move',
					center: false,
					guides: false,
					highlight: false,
					cropBoxMovable: false,
					cropBoxResizable: false,
					toggleDragModeOnDblclick: false,
					ready: function () {
						var cropper = this.cropper
						var containerData = cropper.getContainerData();
						// var imageData = cropper.getImageData()
						// console.log(imageData)
						// if (imageData.aspectRatio >= 1) {
						cropper.setCropBoxData({
							// top: (containerData.height - containerData.width/(150/200))/2,
							// height: imageData.height
							width: containerData.width,
							// left:
						})
						// } else {
						// cropper.setCropBoxData({
						// top: (containerData.height - containerData.width/(150/200))/2,
						// width: containerData.width,
						// width: imageData.width,
						// })
						// }
					}
				});
			}).on('hidden.bs.modal', function () {
				cropper.destroy();
				cropper = null;
			});

			document.getElementById('crop').addEventListener('click', function () {
				var initialAvatarURL;
				var canvas;

				$modal.modal('hide');

				if (cropper) {
					canvas = cropper.getCroppedCanvas({
						width: 150,
						height: 200,
						fillColor: 'white'
					});
					initialAvatarURL = avatar.src;
					avatar.src = canvas.toDataURL();
					$progress.show();
					$alert.removeClass('alert-success alert-warning');
					canvas.toBlob(function (blob) {
						var formData = new FormData();

						formData.append('avatar', blob, 'avatar.jpg');
						$.ajax('https://jsonplaceholder.typicode.com/posts', {
							method: 'POST',
							data: formData,
							processData: false,
							contentType: false,

							xhr: function () {
								var xhr = new XMLHttpRequest();

								xhr.upload.onprogress = function (e) {
									var percent = '0';
									var percentage = '0%';

									if (e.lengthComputable) {
										percent = Math.round((e.loaded / e.total) * 100);
										percentage = percent + '%';
										$progressBar.width(percentage).attr('aria-valuenow', percent).text(percentage);
									}
								};

								return xhr;
							},

							success: function () {
								$alert.show().addClass('alert-success').text('Upload success');
							},

							error: function () {
								avatar.src = initialAvatarURL;
								$alert.show().addClass('alert-warning').text('Upload error');
							},

							complete: function () {
								$progress.hide();
							},
						});
					});
				}
			});
		});
	</script>


</body>

</html>